<?php
// +----------------------------------------------------------------------
// | KITEGO-Admin「开箱即用」「人人全栈」
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2024 https://www.kitego.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed KITEGO并不是自由软件，未经许可不能去掉KITEGO相关版权
// +----------------------------------------------------------------------
// | Author: KITEGO Team <bd@kitego.cn>
// +----------------------------------------------------------------------

namespace kitego\services\common;

class LogService
{
    private $logDir;
    private $baseFileName;
    private $maxFileSize;

    public function __construct($logDir, $baseFileName, $maxFileSize = 5 * 1024 * 1024)
    {
        $this->logDir = rtrim($logDir, '/') . '/';
        $this->baseFileName = $baseFileName;
        $this->maxFileSize = $maxFileSize;

        if (!is_dir($this->logDir)) mkdir($this->logDir, 0755, true);
    }

    public function log($message)
    {
        $logFile = $this->logDir . $this->baseFileName;

        $fileHandle = fopen($logFile, 'a');
        if (!$fileHandle) {
            exception("Failed to open log file: $logFile");
        }

        fwrite($fileHandle, "$message");
        fclose($fileHandle);


        if (filesize($logFile) >= $this->maxFileSize) {
            $this->rotateLog($logFile);
        }
    }

    private function rotateLog($destination)
    {
        rename($destination, dirname($destination) . DIRECTORY_SEPARATOR . date('H-i-s', time()) . '-' . basename($destination));
    }
}